package com.vehicle.cards.controller;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ch.qos.logback.core.joran.spi.XMLUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.vehicle.cards.perpetual.MyPerpetual;
import com.vehicle.cards.service.OssService;
import com.vehicle.cards.utils.HttpUtils;
import com.vehicle.cards.utils.ImageToBase64Utils;
import com.vehicle.cards.utils.MD5Utils;
import com.vehicle.common.core.domain.R;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import com.vehicle.common.log.annotation.Log;
import com.vehicle.common.log.enums.BusinessType;
import com.vehicle.common.security.annotation.PreAuthorize;
import com.vehicle.cards.domain.TIdCards;
import com.vehicle.cards.service.ITIdCardsService;
import com.vehicle.common.core.web.controller.BaseController;
import com.vehicle.common.core.web.domain.AjaxResult;
import com.vehicle.common.core.utils.poi.ExcelUtil;
import com.vehicle.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 身份证Controller
 *
 * @author XU
 * @date 2025-03-28
 */
@RestController
@RequestMapping("/cards")
@Slf4j
public class TIdCardsController extends BaseController
{
    @Autowired
    private ITIdCardsService tIdCardsService;
    @Autowired
    private OssService ossService;


    /**
     * 查询身份证列表
     */
    @PreAuthorize(hasPermi = "cards:cards:list")
    @GetMapping("/list")
    public TableDataInfo list(TIdCards tIdCards)
    {
        startPage();
        List<TIdCards> list = tIdCardsService.selectTIdCardsList(tIdCards);
        return getDataTable(list);
    }

    /**
     * 导出身份证列表
     */
    @PreAuthorize(hasPermi = "cards:cards:export")
    @Log(title = "身份证", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TIdCards tIdCards) throws IOException
    {
        List<TIdCards> list = tIdCardsService.selectTIdCardsList(tIdCards);
        ExcelUtil<TIdCards> util = new ExcelUtil<TIdCards>(TIdCards.class);
        util.exportExcel(response, list, "身份证数据");
    }

    /**
     * 获取身份证详细信息
     */
    @PreAuthorize(hasPermi = "cards:cards:query")
    @GetMapping(value = "/{idCardId}")
    public AjaxResult getInfo(@PathVariable("idCardId") Long idCardId)
    {
        return AjaxResult.success(tIdCardsService.selectTIdCardsByIdCardId(idCardId));
    }

    /**
     * 新增身份证
     */
    @PreAuthorize(hasPermi = "cards:cards:add")
    @Log(title = "身份证", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TIdCards tIdCards)
    {
        return toAjax(tIdCardsService.insertTIdCards(tIdCards));
    }

    /**
     * 修改身份证
     */
    @PreAuthorize(hasPermi = "cards:cards:edit")
    @Log(title = "身份证", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TIdCards tIdCards)
    {
        return toAjax(tIdCardsService.updateTIdCards(tIdCards));
    }

    /**
     * 删除身份证
     */
    @PreAuthorize(hasPermi = "cards:cards:remove")
    @Log(title = "身份证", businessType = BusinessType.DELETE)
	@DeleteMapping("/{idCardIds}")
    public AjaxResult remove(@PathVariable Long[] idCardIds)
    {
        return toAjax(tIdCardsService.deleteTIdCardsByIdCardIds(idCardIds));
    }
    /**
     * 身份证ocr验证
     *
     * @param file
     * @return
     */
    @PostMapping("/idCard")
    public AjaxResult idCard(@RequestParam("file") MultipartFile file) {
        try {
            String timestamp = System.currentTimeMillis() + "";
            String image = ImageToBase64Utils.imageToBase64(file);
            String sign = MD5Utils.encrypt(MyPerpetual.APP_ID + "&" + timestamp + "&" + MyPerpetual.APPSECURITY);

            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/x-www-form-urlencoded");

            Map<String, Object> params = new HashMap<>();
            params.put("appid", MyPerpetual.APP_ID);
            params.put("timestamp", timestamp);
            params.put("sign", sign);
            params.put("image", image);

            String result = HttpUtils.postForm(MyPerpetual.IDCARD_URL, headers, params);
            log.info("OCR返回结果：{}", result);

            JSONObject jsonResult = JSONObject.parseObject(result);
            if (jsonResult != null && jsonResult.getInteger("code") == 200) {
                JSONObject data = jsonResult.getJSONObject("data");
                JSONObject info = data.getJSONObject("info");

                // 构建身份证信息对象
                TIdCards tIdCards = new TIdCards();
                tIdCards.setIdCardNumber(info.getString("number"));
                tIdCards.setName(info.getString("name"));

                // 性别转换
                String sex = info.getString("sex");
                tIdCards.setGender(sex);


                tIdCards.setAddress(info.getString("address"));

                // 处理出生日期
                String year = info.getString("year");
                String month = info.getString("month");
                String day = info.getString("day");
                if (year != null && month != null && day != null) {
                    String birthDate = String.format("%s-%02d-%02d",
                            year,
                            Integer.parseInt(month),
                            Integer.parseInt(day));
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    tIdCards.setBirthDate(sdf.parse(birthDate));
                }

                // 保存到数据库
                int rows = tIdCardsService.insertTIdCards(tIdCards);
                if (rows > 0) {
                    return AjaxResult.success("身份证信息保存成功", tIdCards);
                } else {
                    return AjaxResult.error("保存失败");
                }
            }
            return AjaxResult.error("识别失败");
        } catch (Exception e) {
            log.error("身份证识别失败", e);
            return AjaxResult.error("识别失败：" + e.getMessage());
        }
    }



    /**
     * 人脸识别
     * @param file
     * @return
     */
    @PostMapping("/humanFace")
    public String humanFace(@RequestParam("file") MultipartFile file){

        String uploadFile = ossService.uploadFile(file);
        String humanFace = tIdCardsService.humanFace(uploadFile);

        return humanFace;
    }


}
